package cn.kgc.shiro02.controller;

import cn.hutool.captcha.LineCaptcha;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/4/4
 * @Description:
 */
@Api(tags = "验证码模块")
@Controller
@RequestMapping("captcha")
public class CaptchaController {
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("getCaptcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session){

        LineCaptcha lineCaptcha = new LineCaptcha(110, 50, 4, 3);
        String code = lineCaptcha.getCode();
        // 将 验证码  写入redis缓存  设置生命周期  1min
        redisTemplate.opsForValue().set(session.getId(), code,1, TimeUnit.MINUTES);
        //响应状态码到前端
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            lineCaptcha.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
